import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { recordsApi, systemApi } from '../api/Api';
import { useSockJS } from './useSockJS';
import { useState } from 'react';
import { DeliveryFilter, Order } from '../types';

export function useSystem() {
  const queryClient = useQueryClient();
  const {robotCount,idleRobotCount,robotInfoList,isConnected,mapData,popQueue} = useSockJS();
  const [error, setError] = useState<string | null>(null);
  const [isStop, setIsStop] = useState<boolean>(false);

  //启动
  const startMutation = useMutation({
    mutationFn: async(initRobotCount:number) => {
      const data = await systemApi.startSystem( initRobotCount );
      return data.statusCode;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['systemStatus'] });
      setError(null);
      // 返回的 statusCode 可以通过成功回调传递给 `SystemPage`
    },
    onError: (error) => {
      setError(error?.message || '启动失败');
    }
  });

  //停止
  const stopMutation = useMutation({
    mutationFn: systemApi.stopSystem,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['systemStatus'] });
      setError(null);
      setIsStop(true);
    },
    onError:(error) =>{
      setError(error?.message || '停止失败');
    }
  });

  // 获取已完成的订单
  const { 
    data: orders = [], 
    isLoading: isLoadingCompletedOrders, 
  } = useQuery<Order[]>({
    queryKey: ['completedOrders'],
    queryFn: systemApi.getCompletedOrders,
    refetchInterval: 1000,
  });

  // 获取系统运行时间
  const { 
    data: aliveTime = 0, 
    isLoading: isLoadingAliveTime, 
  } = useQuery<number>({
    queryKey: ['aliveTime'],
    queryFn: systemApi.getAliveTime,
    refetchInterval: 1000, 
  });

  // 计算 records 中 consumedTime 的平均值
  const { data: records = [], isLoading } = useQuery({
    queryKey: ['records'], // 根据filter变化时重新请求
    queryFn: () => recordsApi.getRecords({
      orderNumber: '',
      serialNumber: '',
    }),
    refetchInterval: 2000,  
  });

  const averageConsumedTime = records.length
  ? records.reduce((sum, record) => sum + (record.consumedTime || 0), 0) / records.length
  : 0;
  console.log("timeeeeeeeeeeeeeeeeeeeeeee",averageConsumedTime);

  return {
    robotCount,
    idleRobotCount,
    robotInfoList,
    mapData,
    popQueue,
    completedOrders:orders,
    aliveTime,
    averageConsumedTime,
    isLoading: isConnected || isLoadingCompletedOrders || isLoadingAliveTime,
    error:error,
    startSystem: startMutation.mutate,
    // pauseSystem: pauseMutation.mutate,
    stopSystem: stopMutation.mutate
  };
}